package cc.mrbird.febs.buss.controller;

import cc.mrbird.febs.buss.entity.*;
import cc.mrbird.febs.buss.service.IHallItemService;
import cc.mrbird.febs.buss.util.MyMergeStrategy;
import cc.mrbird.febs.common.annotation.ControllerEndpoint;
import cc.mrbird.febs.common.utils.FebsUtil;
import cc.mrbird.febs.common.entity.FebsConstant;
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.common.entity.QueryRequest;
import cc.mrbird.febs.buss.service.IHallUpDataService;
import cc.mrbird.febs.common.utils.FileUtil;
import cc.mrbird.febs.system.entity.Dept;
import cc.mrbird.febs.system.entity.Role;
import cc.mrbird.febs.system.entity.User;
import cc.mrbird.febs.system.service.IRoleService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.merge.LoopMergeStrategy;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

/**
 *  Controller
 *
 * @author Lujingyuan
 * @date 2020-04-24 14:01:42
 */
@Slf4j
@Validated
@Controller
public class HallUpDataController extends BaseController {

    @Autowired
    private IHallUpDataService hallUpDataService;

    @Autowired
    private IHallItemService hallItemService;

    @Autowired
    private IRoleService roleService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "hallUpData")
    public String hallUpDataIndex(HttpServletRequest req){
        return FebsUtil.view("hallUpData/hallUpData");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hallUpDataAdmin")
    public String hallUpDataAdminIndex(HttpServletRequest req){
        return FebsUtil.view("hallUpData/hallUpData-admin");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hallUpDataAdd")
    public String hallUpDataAdd(HttpServletRequest req){
        return FebsUtil.view("hallUpData/hallUpData-add");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hallUpDataAdminAdd")
    public String hallUpDataAdminAdd(HttpServletRequest req){
        return FebsUtil.view("hallUpData/hallUpDataAdmin-add");
    }

    @GetMapping("hallUpData")
    @ResponseBody
    @RequiresPermissions("hallUpData:list")
    public FebsResponse getAllHallUpDatas(HallUpData hallUpData) {
        return new FebsResponse().success().data(hallUpDataService.findHallUpDatas(hallUpData));
    }

    @GetMapping("hallItemData")
    @ResponseBody
    public FebsResponse getAllHallItemsData(HttpServletRequest req) {
        Enumeration enu=req.getParameterNames();
        HashMap<String,String> map=new HashMap<String,String>();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            map.put(paraName,req.getParameter(paraName));
        }

        User user=this.getCurrentUser();
        List<Role> roleList=this.roleService.findUserRole(user.getUsername());
        boolean isDepart=false;
        boolean isAdmin=false;
        for(Role role:roleList){
            if("zz_zdxq_depart".equals(role.getRemark())){
                isDepart=true;
                map.put("depart",user.getDeptId()+"");
            }
            if("zz_zdxq_hall".equals(role.getRemark())){
                isAdmin=true;
            }
        }

        List<HallItem> itemList=hallItemService.findHallItemByMap(map);
        List<JsonEntity> jsonList=new ArrayList<>();
        Boolean isUpdate=true;
        for(HallItem item:itemList){
            Map datamap=new HashMap<String,String>();
            datamap.put("item",item.getId());
            datamap.put("dataType","0");
            datamap.put("bussTime",map.get("buss_time"));
            List<HallUpData> datalist=hallUpDataService.getUpData(map.get("buss_time"),item.getId(),"0");
            HallUpData d=new HallUpData();
            if(datalist!=null&&datalist.size()>0){
                d=datalist.get(0);
                if(isDepart){
                    isUpdate=false;
                }
            }
            d.setSeekBussCount(d.getSeekBussCount()==null?0:d.getSeekBussCount());
            d.setMailBussCount(d.getMailBussCount()==null?0:d.getMailBussCount());
            d.setOnlineBussCount(d.getOnlineBussCount()==null?0:d.getOnlineBussCount());
            d.setUnderlineHall(d.getUnderlineHall()==null?0:d.getUnderlineHall());
            d.setUnderlineSubHall(d.getUnderlineSubHall()==null?0:d.getUnderlineSubHall());
            JsonEntity je=new JsonEntity();
            je.setHallUpData(d);
            je.setItem(item);
            jsonList.add(je);
        }

        return new FebsResponse().success().data(jsonList).put("isUpdate",isUpdate);
    }

    @GetMapping("hallUpData/list")
    @ResponseBody
    public FebsResponse hallUpDataList(QueryRequest request, HttpServletRequest req, HallUpData hallUpData) {
        Enumeration enu=req.getParameterNames();
        HashMap<String,String> map=new HashMap<String,String>();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            map.put(paraName,req.getParameter(paraName));
        }
        Map<String, Object> dataTable = getDataTable(this.hallUpDataService.findHallUpDataDetail(request, map));
        return new FebsResponse().success().data(dataTable);
    }

    @GetMapping("hallUpData/resultData")
    @ResponseBody
    public FebsResponse hallUpDataResult(HttpServletRequest req){
        Enumeration enu=req.getParameterNames();
        HashMap<String,String> map=new HashMap<String,String>();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            map.put(paraName,req.getParameter(paraName));
        }
        if(StringUtils.isBlank(map.get("departId"))){
            User user=this.getCurrentUser();
            List<Role> roleList=this.roleService.findUserRole(user.getUsername());
            boolean isDepart=false;
            for(Role role:roleList){
                if("zz_zdxq_depart".equals(role.getRemark())){
                    isDepart=true;
                    map.put("departId",user.getDeptId()+"");
                }
            }
        }
        List<DepartResultData> list=hallUpDataService.getDepartResultDataList(map);
        return new FebsResponse().success().data(list);
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hallUpData/add")
    public String goHallUpDataAdd(HttpServletRequest req) {
        List<HallItem> list=hallItemService.list();
        req.setAttribute("list",list);
        return FebsUtil.view("hallUpData/hallUpDataAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hallUpData/update/{id}")
    public String goHallUpDataUpdate(@PathVariable String id, Model model) {
        HallUpData obj= hallUpDataService.getById(id);
        model.addAttribute("obj",obj);
        return FebsUtil.view("hallUpData/hallUpDataUpdate");
    }

    @ControllerEndpoint(operation = "新增HallUpData", exceptionMessage = "新增HallUpData失败")
    @PostMapping("hallUpData")
    @ResponseBody
    public FebsResponse addHallUpData(@Valid HallUpData hallUpData) {
        this.hallUpDataService.createHallUpData(hallUpData);
        return new FebsResponse().success();
    }

    @ControllerEndpoint(operation = "上传数据", exceptionMessage = "上传数据失败")
    @PostMapping("pushData")
    @ResponseBody
    public FebsResponse pushData(HttpServletRequest req) throws ParseException {
        String tr_data=req.getParameter("tr_data");
        String answer_count=req.getParameter("answer_count");
        String post_count=req.getParameter("post_count");
        String buss_time=req.getParameter("buss_time");
        Date date=new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date buss_date=sdf.parse(buss_time);
        User user=this.getCurrentUser();
        Long departId;
        if(StringUtils.isEmpty(req.getParameter("depart"))){
            departId=user.getDeptId();
        }else{
            departId=Long.parseLong(req.getParameter("depart"));
        }
        if(StringUtils.isNotBlank(tr_data)&&StringUtils.isNotBlank(answer_count)&&StringUtils.isNotBlank(answer_count)){
            String[] trArray=tr_data.split(",");
            Integer seekBussCount=Integer.parseInt(answer_count);
            Integer mailBussCount=Integer.parseInt(post_count);
            for(String trStr:trArray){
                if(StringUtils.isNotBlank(trStr)){
                    String[] arr=trStr.split("_");
                    if(arr!=null&&arr.length==4){
                        Long id=Long.parseLong(arr[0]);
                        Integer onlineBussCount=Integer.parseInt(arr[1]);
                        Integer underlineHallBussCount=Integer.parseInt(arr[2]);
                        Integer underlineSubHallBussCount=Integer.parseInt(arr[3]);
                        HallUpData upData=new HallUpData();
                        upData.setDepart(departId);
                        upData.setItem(id);
                        upData.setDataType("0");
                        upData.setIsDel(0);
                        upData.setBussTime(buss_date);
                        upData.setCreateTime(date);
                        upData.setOnlineBussCount(onlineBussCount);
                        upData.setUnderlineHall(underlineHallBussCount);
                        upData.setUnderlineSubHall(underlineSubHallBussCount);
                        upData.setSeekBussCount(seekBussCount);
                        upData.setMailBussCount(mailBussCount);
                        this.hallUpDataService.deleteDataByTime(buss_time,id,"0");
                        this.hallUpDataService.save(upData);
                    }
                }
            }


            HallUpData deptData=new HallUpData();
            deptData.setDepart(departId);
            deptData.setDataType("1");
            deptData.setIsDel(0);
            deptData.setBussTime(buss_date);
            deptData.setCreateTime(date);
            deptData.setSeekBussCount(seekBussCount);
            deptData.setMailBussCount(mailBussCount);
            this.hallUpDataService.deleteDataByTime(buss_time,departId,"1");
            this.hallUpDataService.save(deptData);
            return new FebsResponse().success();
        }
        return new FebsResponse().fail();
    }

    @GetMapping("hallUpData/delete/{objIds}")
    @ControllerEndpoint(operation = "删除", exceptionMessage = "删除失败")
    @ResponseBody
    public FebsResponse deleteHallUpData( @PathVariable String objIds) {
        String[] ids = objIds.split(StringPool.COMMA);
        this.hallUpDataService.deleteHallUpData(ids);
        return new FebsResponse().success();
    }

    @ControllerEndpoint(operation = "修改HallUpData", exceptionMessage = "修改HallUpData失败")
    @PostMapping("hallUpData/update")
    @ResponseBody
    public FebsResponse updateHallUpData(HallUpData hallUpData) {
        this.hallUpDataService.updateHallUpData(hallUpData);
        return new FebsResponse().success();
    }


    @GetMapping("resultData/exportInfo")
    @ControllerEndpoint(exceptionMessage = "导出Excel失败")
    public void exportInfo(HttpServletRequest req, HttpServletResponse response) throws Exception {
        Enumeration enu=req.getParameterNames();
        HashMap<String,String> map=new HashMap<String,String>();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            map.put(paraName,req.getParameter(paraName));
        }
        if(StringUtils.isBlank(map.get("departId"))){
            User user=this.getCurrentUser();
            List<Role> roleList=this.roleService.findUserRole(user.getUsername());
            boolean isDepart=false;
            for(Role role:roleList){
                if("zz_zdxq_depart".equals(role.getRemark())){
                    isDepart=true;
                    map.put("departId",user.getDeptId()+"");
                }
            }
        }
        List<HallUpData> datalist=new ArrayList<HallUpData>();
        List<DepartResultData> departResultDatalist=hallUpDataService.getDepartResultDataList(map);
        for(DepartResultData departResultData:departResultDatalist){
            datalist.addAll(departResultData.getDataList());
        }
        //List<HallUpData> datalist=hallUpDataService.getResultDataList(map);
        List<ResultData> list=new ArrayList<ResultData>();
        List<Integer> countList=new ArrayList<Integer>();
        Map<String,Integer> countmap=new HashMap<String,Integer>();
        for(HallUpData ud:datalist){
            ResultData rd=new ResultData();
            rd.setDeptName(ud.getDepartName());
            rd.setMainItemName(ud.getMainItemName());
            rd.setSumItemName(ud.getSumItemName());
            rd.setItemType(ud.getItemType());
            rd.setItemName(ud.getItemName());
            rd.setSeekBussCount(ud.getSeekBussCount()+"");
            rd.setMailBussCount(ud.getMailBussCount()+"");
            rd.setOnlineBussCount(ud.getOnlineBussCount()+"");
            rd.setUnderlineHall(ud.getUnderlineHall()+"");
            rd.setUnderlineSubHall(ud.getUnderlineSubHall()+"");

            HallItem item=hallItemService.getById(ud.getItem());
            if(item!=null){
                rd.setAddressType(item.getAddressType());
                rd.setServiceObject(item.getServiceObject());
                rd.setImmediately(item.getImmediately());
                rd.setNeedCard(item.getNeedCard());
                rd.setAllCityHandle(item.getAllCityHandle());
                rd.setAtMostOnce(item.getAtMostOnce());
                rd.setZeroRun(item.getZeroRun());
                rd.setOnlineCheck(item.getOnlineCheck());
                rd.setBussSystem(item.getBussSystem());
            }
            list.add(rd);
            if(countmap.get(rd.getDeptName())==null){
                countmap.put(rd.getDeptName(),1);
            }else{
                Integer count=countmap.get(rd.getDeptName());
                count+=1;
                countmap.put(rd.getDeptName(),count);
            }
        }
        for(Map.Entry<String, Integer> entry : countmap.entrySet()){
            Integer mapValue = entry.getValue();
            if(mapValue!=null){
                countList.add(mapValue);
            }
        }
        //ExcelKit.$Export(UserInfo.class, response).downXlsx(eximports, false);
        String fileName= "D:\\"+System.currentTimeMillis() + ".xlsx";

        MyMergeStrategy myMergeStrategy = new MyMergeStrategy(list, countList);
        EasyExcel.write(fileName, ResultData.class).registerWriteHandler(myMergeStrategy).sheet("业务统计").doWrite(list);
        FileUtil.download(fileName,"aaab",false,response);
        System.out.println("excel文档下载成功");
    }


}
